package com.wss.common.manage;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.TransformationUtils;
import com.wss.common.utils.PxUtils;
import ohos.agp.render.*;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

import java.security.MessageDigest;

public class GlideRoundTransform extends BitmapTransformation {

    private float radius = 0f;

    public GlideRoundTransform(Context context, int vp) {
        super();
        radius = PxUtils.vp2px(vp);
    }

    @Override
    protected PixelMap transform(@NotNull BitmapPool bitmapPool, @NotNull PixelMap pixelMap, int outWidth, int outHeight) {
        PixelMap pixelmap = TransformationUtils.centerCrop(bitmapPool, pixelMap, outWidth, outHeight);
        return roundCrop(bitmapPool, pixelmap);
    }

    @Contract("_, null -> null")
    private PixelMap roundCrop(BitmapPool pool, PixelMap source) {
        if (source == null){ return null;}
        PixelMap result = pool.get(source.getImageInfo().size.width,
                source.getImageInfo().size.height,
                PixelFormat.ARGB_8888);

        Canvas canvas = new Canvas(new Texture(source));
        Paint paint = new Paint();
        paint.setShader(new PixelMapShader(new PixelMapHolder(source), PixelMapShader.TileMode.CLAMP_TILEMODE, PixelMapShader.TileMode.CLAMP_TILEMODE), Paint.ShaderType.LINEAR_SHADER);
        paint.setAntiAlias(true);
        RectFloat rectF = new RectFloat(0f,
                0f,
                source.getImageInfo().size.width,
                source.getImageInfo().size.height);
        canvas.drawRoundRect(rectF, radius, radius, paint);
        return result;
    }

    public String getId() {
        return getClass().getName() + Math.round(radius);
    }

    @Override
    public void updateDiskCacheKey(@NotNull MessageDigest messageDigest) {

    }
}
